
import 'package:ble2025_plugin/ble2203_plugin.dart';
import 'package:flutter/foundation.dart';

class OtaSendData{
  ///检查是否需要升级
  static Uint8List checkUpdateFile(List<int> binByte, List<int> binMd5,int fileNumber) {
    return _checkFile(binByte, binMd5, 1, fileNumber);
  }
  static int cmdCheck = 0x92;

  ///
  ///  binByte    整个文件字节
  ///  binMd5     整个文件md5
  ///  mode       1，检查是否需要升级，2 升级结束后的检查
  ///  fileNumber 文件类型，暂时为0，后期扩展
  static Uint8List _checkFile(List<int> binByte, List<int> binMd5, int mode, int fileNumber) {
    int length = binByte.length;
    int crc16 = CalcCRC16(binByte, binByte.length);
    List<int> value = generateValue(27);
    value[0] = cmdCheck;
    value[1] = mode;
    value[2] = fileNumber;
    value[3] = ((length) & 0xff);//低位在前
    value[4] = ((length >> 8) & 0xff);
    value[5] = ((length >> 16) & 0xff);
    value[6] = ((length >> 24) & 0xff);
    value[7] = ((crc16) & 0xff);
    value[8] = ((crc16 >> 8) & 0xff);
    BleSDK.arrayCopy(binMd5, 0, value, 9, binMd5.length);
    int crcValue16 = CalcCRC16(value, 25);
    value[25] = ((crcValue16) & 0xff);
    value[26] = ((crcValue16 >> 8) & 0xff);
    return Uint8List.fromList(value);
  }


  static Uint8List endUpdateFile(List<int> binByte, List<int> binMd5,int fileNumber) {//数据全部发送完成检查是否升级成功
    return _checkFile(binByte, binMd5, 2, fileNumber);
  }

  static int CalcCRC16(List<int> pArray,int length) {
    int wCRC = 0xFFFF;
    int CRC_Count = length;
    int i;
    int num = 0;
    while (CRC_Count > 0)
    {
      CRC_Count--;
      wCRC = wCRC ^ (0xFF & pArray[num++]);
      for (i = 0; i < 8; i++)
      {
        if ((wCRC & 0x0001) == 1)
        {
          wCRC = wCRC >> 1 ^ 0xA001;
        }
        else
        {
          wCRC = wCRC >> 1;
        }
      }
    }
    return wCRC;
  }

  static List<int> generateValue(int size) {
    final List<int> data = List<int>.generate(size, (int index) {
      return 0;
    });
    return data;
  }
}